package com.molin.conllectionTest;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class Demo4 {
    //利用迭代器删除集合中的元素
    public static void main(String[] args) {
        ArrayList<String> collection=new ArrayList<String>();
        collection.add("a");
        collection.add("b");
        collection.add("b");
        collection.add("c");
        collection.add("d");
//        foriRemove(collection);
        iteratorRemove(collection);

        System.out.println(collection);
    }

    private static void iteratorRemove(ArrayList<String> collection) {
        Iterator<String> iterator=collection.iterator();
        while (iterator.hasNext()){
            if (iterator.next().equals("b")){
                iterator.remove();//迭代器无需担心列表自动缩进
            }
        }
    }

    private static void foriRemove(ArrayList<String> collection) {
        for (int i = 0; i < collection.size(); i++) {
            String s=collection.get(i);
            if("b".equals(s)){
                collection.remove(i);
                i--;//列表（集合）会自动缩进!
            }
        }
    }
}
